Page({
    data: {
      latitude: 0,
      tabIndex: 2,
      longitude: 0,
      markers: [],
      pets: [],
      selectedPet: null,
      distanceOptions: ['全部', '1km', '3km', '5km'],
      selectedDistanceIndex: 0, // 默认是“全部”
      distanceLimit: 0, // 对应实际距离值
    },
  
    onLoad() {
      wx.authorize({
        scope: 'scope.userLocation',
        success: () => {
          wx.getLocation({
            type: 'gcj02',
            success: (res) => {
              const { latitude, longitude } = res;
              this.setData({ latitude, longitude });
              this.loadPetsNearby(latitude, longitude);
            }
          });
        },
        fail: () => {
          wx.showModal({
            title: '提示',
            content: '需要授权地理位置才能展示附近的宠物信息',
            success(res) {
              if (res.confirm) wx.openSetting();
            }
          });
        }
      });
    },
    onTabChange(e) {
        const index = e.detail.index;
        const tabPages = [
          '/pages/index/index',
          '/pages/cart/cart',
          '/pages/map-pet/map-pet',
          '/pages/settings/settings'
        ];
        if (index === this.data.tabIndex) return;
        wx.switchTab({
          url: tabPages[index]
        });
      },
      onDistanceSelect(e) {
        const km = Number(e.currentTarget.dataset.distance);
        this.setData({ distanceLimit: km }, () => {
          this.updateVisiblePets();
        });
      },
      onDistancePickerChange(e) {
        const index = Number(e.detail.value);
        const distanceValues = [0, 1, 3, 5]; // 和 options 对应
      
        this.setData({
          selectedDistanceIndex: index,
          distanceLimit: distanceValues[index]
        }, () => {
          this.updateVisiblePets();
        });
      },      
      loadPetsNearby(lat, lng) {
        const pets = [
          {
            id: '1',
            name: 'Mimi',
            age: '2个月',
            img: '/images/pets/brid3.jpg',
            latitude: lat + 0.002,
            longitude: lng + 0.003
          },
          {
            id: '2',
            name: 'Dodo',
            age: '4个月',
            img: '/images/pets/brid2.jpg',
            latitude: lat - 0.001,
            longitude: lng - 0.002
          }
        ];
      
        // 计算距离
        const petsWithDistance = pets.map(pet => {
          const dx = 111 * (pet.latitude - lat);
          const dy = 111 * (pet.longitude - lng);
          const distance = Math.sqrt(dx * dx + dy * dy).toFixed(2);
          return { ...pet, distance };
        });
      
        // markers用宠物头像
        const markers = petsWithDistance.map(pet => ({
          id: pet.id,
          latitude: pet.latitude,
          longitude: pet.longitude,
          iconPath: pet.img,  // 宠物头像作为图标
          width: 50,
          height: 50
        }));
      
        this.setData({ markers, pets: petsWithDistance });
      },
    updateVisiblePets() {
        const { allPets, distanceLimit } = this.data;
        let filteredPets = allPets;
      
        if (distanceLimit > 0) {
          filteredPets = allPets.filter(p => parseFloat(p.distance) <= distanceLimit);
        }
      
        const markers = filteredPets.map(pet => ({
          id: pet.id,
          latitude: pet.latitude,
          longitude: pet.longitude,
          iconPath: '/images/icon/pet-marker.png',
          width: 40,
          height: 40
        }));
      
        this.setData({
          pets: filteredPets,
          markers,
          selectedPet: null // 重置当前弹窗
        });
      },
      
    onMarkerTap(e) {
      const pet = this.data.pets.find(p => String(p.id) === String(e.markerId));
      if (pet) {
        this.setData({ selectedPet: pet });
      }
    },
  
    goToPetDetail() {
        const pet = this.data.selectedPet;
        if (!pet) return;
      
        wx.navigateTo({
          url: '/pages/pet-detail/pet-detail',
          success(res) {
            // 传递数据
            res.eventChannel.emit('petData', { pet });
          },
          fail(err) {
            console.error('跳转失败:', err);
          }
        });
      }
  });
  